package com.finace.money.net.socket;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import com.finace.money.App;
import com.finace.money.common.util.ACacheClearUtil;
import com.finace.money.common.util.LogUtil;
import com.finace.money.common.util.UIUtil;

/**
 * Created by zhangpeng on 2017/12/8.
 */

public class ConnService extends Service implements ConnManager.ConnectionListener {

    private ConnManager mConnManager;
    private Thread thread;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    /**
     * 连接服务
     */
    @Override
    public void onCreate() {
        super.onCreate();
        if(!App.isAppOnForeground(UIUtil.getContext())){
            LogUtil.d("APPP","不在前台");
            stopSelf();//杀掉自己
            return;
        }
        if(null != thread){
            thread = null;
        }
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                mConnManager = ConnManager.getInstance();
                mConnManager.setConnectionListener(ConnService.this);
                mConnManager.connect();

            }
        });
        thread.start();

    }

    @Override
    public void pushData(String data) {
        Intent intent = new Intent();
        intent.setAction(PushReceiver.ACTION);
        intent.putExtra(PushReceiver.DATA, data);
        sendBroadcast(intent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d("APPP","被杀掉了");
        ACacheClearUtil.loginOut();
        if(null != thread){
            thread = null;
        }
        if(null != mConnManager){
            mConnManager.disConnect();
        }
    }
}
